package com.youlu.campus.service.learning.impl;

import com.alibaba.fastjson.JSON;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.common.utils.DateTimeUtils;
import com.youlu.campus.common.utils.TimeUtils;
import com.youlu.campus.entity.ActivityInfo;
import com.youlu.campus.entity.ActivityTaskInfo;
import com.youlu.campus.entity.DailyLearning;
import com.youlu.campus.entity.UserActivityPointDetail;
import com.youlu.campus.entity.UserActivityTaskInfo;
import com.youlu.campus.entity.UserDailyLearning;
import com.youlu.campus.entity.UserPO;
import com.youlu.campus.entity.UserParticipateActivityInfo;
import com.youlu.campus.entity.VO.req.DailyLearningQueryVO;
import com.youlu.campus.entity.VO.req.UserDailyLearningCreateVO;
import com.youlu.campus.entity.domain.PlayBillDomain;
import com.youlu.campus.entity.enums.TaskBizType;
import com.youlu.campus.service.activity.ActivityService;
import com.youlu.campus.service.activity.UserParticipateActivityInfoService;
import com.youlu.campus.service.aomen.AoMenService;
import com.youlu.campus.service.base.LockService;
import com.youlu.campus.service.learning.DailyLearningService;
import com.youlu.campus.service.platform.PlatformConfigService;
import com.youlu.campus.service.ranking.UserActivityPointDetailService;
import com.youlu.campus.service.ranking.UserActivityPointRankingProvinceService;
import com.youlu.campus.service.ranking.UserActivityPointRankingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.youlu.campus.base.common.Constants.ACTIVITY__V2;

@Slf4j
@Service
public class DailyLearningServiceImpl implements DailyLearningService {
    @Autowired
    private ActivityService activityService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Value("${sys.defaultHeadUrl}")
    private String defaultHeadUrl;
    @Autowired
    private PlatformConfigService platformConfigService;
    @Autowired
    private LockService lockService;
    @Autowired
    private UserActivityPointRankingService userActivityPointRankingService;
    @Autowired
    private UserActivityPointDetailService userActivityPointDetailService;
    @Autowired
    private UserActivityPointRankingProvinceService userActivityPointRankingProvinceService;

    @Autowired
    private AoMenService aoMenService;

    @Resource(name = "masterMongoTemplate")
    private MongoTemplate masterMongoTemplate;

    @Lazy
    @Autowired
    private UserParticipateActivityInfoService userParticipateActivityInfoService;

    @Autowired
    private StringRedisTemplate redisTemplateLock;


    private final String USER_DAILY_LEARNING_LOCK = "daily:learning:lock:%s:%s:%s:";

    @Override
    public UserDailyLearning getUserDailyLearning(String activityId, ActivityTaskInfo taskInfo, String userId) {
        log.info(":>>> 开始获取用户每日签到:{},{},{}", activityId, taskInfo.getId(), userId);
        Date date = new Date();
        DailyLearning dailyLearning = this.getDailyLearning(activityId, taskInfo.getId(), date);
        dailyLearning.setHasShare(taskInfo.getHasShare());
        dailyLearning.setTips(taskInfo.getTips());
        UserDailyLearning userDailyLearning = this.getUserDailyLearning(activityId, taskInfo.getId(), userId, date);
        if (Objects.isNull(userDailyLearning)) {
            userDailyLearning = new UserDailyLearning();
            userDailyLearning.setActivityId(activityId);
            userDailyLearning.setTaskId(taskInfo.getId());
            userDailyLearning.setStatus(0);
            userDailyLearning.setUserId(userId);
            userDailyLearning.setDayTime(date);
        }
        if (Boolean.TRUE.equals(taskInfo.getHasShare())) {
            UserDailyLearning u = new UserDailyLearning();
//            u.setDailyLearningId(dailyLearning.getId());
            u.setUserId(userId);
            u.setTaskId(dailyLearning.getTaskId());
            Long count = this.getUserDailyLearningCount(u);
            if (count.intValue() == 0) {
                userDailyLearning.setTips("开始学习吧,获取更多志愿时长!");
            } else {
                String tips = String.format("当前已累计学习%d天，共获得%s志愿时长", count.intValue(), (count * taskInfo.getRatio()) + "");
                userDailyLearning.setTips(tips);
            }
        }
        userDailyLearning.setLayoutNo(taskInfo.getLayoutNo());
        userDailyLearning.setHeaderTips(taskInfo.getHeaderTips());
        userDailyLearning.setHeaderSubTips(taskInfo.getHeaderSubTips());
        userDailyLearning.setDailyLearning(dailyLearning);
        userDailyLearning.setPoint(taskInfo.getPoints().intValue());
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.addCriteria(Criteria.where("activityId").is(activityId));
        UserParticipateActivityInfo user = this.masterMongoTemplate.findOne(query, UserParticipateActivityInfo.class);
        if (Objects.nonNull(user)) {
            String otherPlatformOpenId = user.getOtherPlatformOpenId();
            if (StringUtils.isNotBlank(otherPlatformOpenId)) {
                String redirectUriCoupon = aoMenService.getRedirectUriCoupon(otherPlatformOpenId);
                log.info("【万博会】redirect url ->{} openid ->{}", redirectUriCoupon, otherPlatformOpenId);
                userDailyLearning.setRedirectUriCoupon(redirectUriCoupon);
            }
        }
        return userDailyLearning;
    }

    @Override
    public boolean signUp(UserDailyLearningCreateVO req) {
        log.info(":>>> 开始签到学习:{}", JSON.toJSONString(req));
        Date date = new Date();

        String nowDate = DateTimeUtils.formatDate(date, "yyyyMMdd");
        String lockKey = String.format(USER_DAILY_LEARNING_LOCK, req.getUserId(), req.getActivityId(), nowDate);
        Boolean existKey = redisTemplateLock.opsForValue().setIfAbsent(lockKey, "1", 10, TimeUnit.MINUTES);
        log.info("【打卡签到】获取锁状态->{}", existKey);
        if (Objects.nonNull(existKey) && !existKey) {
            log.error(":>>> 用户:{} 已经签到:{} ,不要重复签到 lock", req.getUserId(), req.getActivityId());
            return Boolean.TRUE;
        }
        //DailyLearning dailyLearning = this.getDgetDailyLearningailyLearning(req.getActivityId(), req.getTaskId(), date);
        UserDailyLearning userDailyLearning = this.getUserDailyLearning(req.getActivityId(), req.getTaskId(), req.getUserId(), date);
        if (Objects.nonNull(userDailyLearning)) {
            log.error(":>>> 用户:{} 已经签到:{} ,不要重复签到", req.getUserId(), req.getActivityId());
            return true;
        }
        ActivityTaskInfo learningTask = activityService.getTaskInfo(req.getActivityId(), TaskBizType.LEARNING);
        userDailyLearning = new UserDailyLearning();
        userDailyLearning.setActivityId(req.getActivityId());
        userDailyLearning.setTaskId(req.getTaskId());
        userDailyLearning.setStatus(1);
        userDailyLearning.setUserId(req.getUserId());
        userDailyLearning.setDayTime(date);
        userDailyLearning.setDoneTime(date);
        userDailyLearning.setCreatedTime(date);
        ActivityInfo activityInfo = activityService.findOne(req.getActivityId());
        userDailyLearning.setActivityName(activityInfo == null ? null : activityInfo.getName());
        mongoTemplate.insert(userDailyLearning);

        //更新每日签到天数
        userParticipateActivityInfoService.updateSignInDay(req.getUserId(), req.getActivityId());

        if (Arrays.asList(ACTIVITY__V2).contains(activityInfo.getType())) {
            UserActivityTaskInfo u = new UserActivityTaskInfo();
            u.setTaskBizType(TaskBizType.LEARNING);
            u.setActivityId(req.getActivityId());
            u.setTaskId(learningTask.getId());
            u.setDoType("day");
            u.setStatus(2);
            u.setUserId(req.getUserPO().getId());
            u.setCreatedTime(date);
            u.setDayTime(TimeUtils.getDayStartTime(date));
            u.setDoneTime(date);
            mongoTemplate.insert(u);
            Integer point = learningTask.getPoints().intValue();
            if (Boolean.TRUE.equals(req.getHasAd())) {
                point = point * 3;
            }
            UserActivityPointDetail detail = new UserActivityPointDetail();
            detail.setActivityId(req.getActivityId());
            detail.setUserId(req.getUserId());
            detail.setUserPO(req.getUserPO());
            detail.setPoints(point);
            detail.setAction("add");
            detail.setBizDesc("每日学习获得");
            detail.setBizType("learning");
            userActivityPointDetailService.create(detail);
            userActivityPointRankingProvinceService.updatePoint(req.getUserPO(), req.getActivityId(), point);
        } else {
            activityService.updateRank(req.getUserPO(), req.getActivityId(), learningTask.getPoints());
        }
        return true;
    }

    @Override
    public DailyLearning getDailyLearning(String activityId, String taskId, Date date) {

        Date dayStart = TimeUtils.getDayStartTime(date);
        Date dayEnd = TimeUtils.getDayEndTime(date);
        Query query = new Query().addCriteria(Criteria.where("activityId").is(activityId).and("taskId").is(taskId).andOperator(
                Criteria.where("dayTime").lte(dayEnd), Criteria.where("dayTime").gte(dayStart)));
        DailyLearning dailyLearning = mongoTemplate.findOne(query, DailyLearning.class);
        if (Objects.isNull(dailyLearning)) {
            log.error(":>>> 活动:{}: 天: {} 签到任务不存在", date);
            throw new BusinessException("签到任务不存在");
        }
        return dailyLearning;
    }

    @Override
    public UserDailyLearning getUserDailyLearning(String activityId, String taskId, String userId, Date date) {
        Date dayStart = TimeUtils.getDayStartTime(date);
        Date dayEnd = TimeUtils.getDayEndTime(date);
        log.info(":>>> 日期:{},天开始时间:{},天结束时间:{}", date, dayStart, dayEnd);
        Query query = new Query().addCriteria(Criteria.where("userId").is(userId).and("taskId").is(taskId).andOperator(
                Criteria.where("dayTime").lte(dayEnd), Criteria.where("dayTime").gte(dayStart)));
        UserDailyLearning dailyLearning = mongoTemplate.findOne(query, UserDailyLearning.class);
        log.info(":>>> 活动:{},任务:{},用户:{},日期:{} ,签到信息:{}", activityId, taskId, userId, date, JSON.toJSONString(dailyLearning));
        return dailyLearning;
    }

    @Override
    public Page<DailyLearning> list(DailyLearningQueryVO req) {
        log.info(":>>> 开始获取每日学习列表:{}", JSON.toJSONString(req));
        if (Objects.isNull(req)) {
            log.error(":>>> 每日学习参数错误");
            throw new BusinessException("每日学习参数错误");
        }
        Query query = new Query();
        if (StringUtils.isNotBlank(req.getActivityId())) {
            query.addCriteria(Criteria.where("activityId").is(req.getActivityId()));
        }
        if (req.getStartTime() != null || req.getEndTime() != null) {
            Criteria criteria = Criteria.where("dayTime");
            if (req.getStartTime() != null) {
                criteria.gte(req.getStartTime());
            }
            if (req.getEndTime() != null) {
                criteria.lte(req.getEndTime());
            }
            query.addCriteria(criteria);
        }
        long count = mongoTemplate.count(query, DailyLearning.class);
        PageRequest pageRequest = PageRequest.of(req.getPage() - 1, req.getPageSize());
//        query.with(new Sort(Sort.Direction.DESC, "payTime"));
        Sort sort = Sort.by(Sort.Direction.DESC, "dayTime");
        query.with(sort);
        List<DailyLearning> orderPOS = mongoTemplate.find(query.with(pageRequest), DailyLearning.class);
        return PageableExecutionUtils.getPage(orderPOS, pageRequest, () -> count);
    }

    @Override
    public boolean create(DailyLearning req) {
        log.info(":>>> 开始创建每日学习列表:{}", JSON.toJSONString(req));
        if (Objects.isNull(req) || StringUtils.isBlank(req.getActivityId()) || StringUtils.isBlank(req.getTitle()) || StringUtils.isBlank(req.getImageUrl())) {
            log.error(":?>> 创建每日学习参数错误:");
            throw new BusinessException("创建每日学习参数错误");
        }
        ActivityInfo activityInfo = activityService.findOne(req.getActivityId());
        if (Objects.isNull(activityInfo)) {
            log.error(":?>> 创建每日学习活动不存在:{}", req.getActivityId());
            throw new BusinessException("创建每日学习活动不存在");
        }
        ActivityTaskInfo activityTaskInfo = activityService.getTaskInfo(req.getActivityId(), TaskBizType.LEARNING);
        if (Objects.isNull(activityTaskInfo)) {
            log.error(":?>> 创建每日学习活动任务不存在:{}", req.getActivityId());
            throw new BusinessException("创建每日学习任务不存在");
        }
//        if (Boolean.TRUE.equals(activityTaskInfo.getHasShare())) {
//            if (Objects.isNull(req.getPlayBillDomain()) || StringUtils.isBlank(req.getPlayBillDomain().getPlayBillImageUrl()) ||
//                    StringUtils.isBlank(req.getPlayBillDomain().getPlayBillImageUrlQQH5())) {
//                log.error(":>>> 海报信息错误");
//                throw new BusinessException("创建每日学习任务海报信息错误");
//            }
//        }
        Date date = req.getDayTime();
        if (Objects.isNull(date)) {
            date = new Date();
            log.error(":>>> 签到任务日期为空:设置为当天:{}", date);
        }
        Date dayStart = TimeUtils.getDayStartTime(date);
        req.setActivityId(req.getActivityId());
        req.setActivityName(activityInfo.getName());
        req.setId(null);
        req.setTaskId(activityTaskInfo.getId());
        req.setDayTime(dayStart);
        PlayBillDomain playBill = activityTaskInfo.getPlayBill();
        if (Objects.nonNull(playBill)) {
            playBill.setProps(activityTaskInfo.getProps());
            playBill.setPlayBillImageUrl(req.getPlayBillDomain().getPlayBillImageUrl());
            playBill.setPlayBillImageUrlQQH5(req.getPlayBillDomain().getPlayBillImageUrlQQH5());
            req.setPlayBillDomain(playBill);
        }
        req.setPosterImgUrl(req.getPosterImgUrl());
        mongoTemplate.insert(req);
        return true;
    }

    @Override
    public boolean update(DailyLearning req) {
        if (Objects.isNull(req) || StringUtils.isBlank(req.getId())) {
            log.error(":?>> 修改每日学习参数错误:");
            throw new BusinessException("修改每日学习参数错误");
        }
        ActivityTaskInfo activityTaskInfo = activityService.getTaskInfo(req.getActivityId(), TaskBizType.LEARNING);
        if (Objects.isNull(activityTaskInfo)) {
            log.error(":?>> 创建每日学习活动任务不存在:{}", req.getActivityId());
            throw new BusinessException("创建每日学习任务不存在");
        }
        Query query = new Query().addCriteria(Criteria.where("id").is(req.getId()));
        DailyLearning dailyLearningEx = mongoTemplate.findOne(query, DailyLearning.class);
        if (Objects.isNull(dailyLearningEx)) {
            log.error(":>>> 每日学习不存在:{}", req.getId());
            throw new BusinessException("每日学习不存在");
        }
        Update update = new Update();
        if (StringUtils.isNotBlank(req.getTitle())) {
            update.set("title", req.getTitle());
        }
        if (StringUtils.isNotBlank(req.getImageUrl())) {
            update.set("imageUrl", req.getImageUrl());
        }
        if (Objects.nonNull(req.getDayTime())) {
            update.set("dayTime", req.getDayTime());
        }
        if (StringUtils.isNotBlank(req.getPosterImgUrl())) {
            update.set("posterImgUrl", req.getPosterImgUrl());
        }
        update.set("updatedTime", new Date());
//        if (Boolean.TRUE.equals(activityTaskInfo.getHasShare())) {
//            if (Objects.isNull(req.getPlayBillDomain()) || StringUtils.isBlank(req.getPlayBillDomain().getPlayBillImageUrl()) ||
//                    StringUtils.isBlank(req.getPlayBillDomain().getPlayBillImageUrlQQH5())) {
//                log.error(":>>> 海报信息错误");
//                throw new BusinessException("创建每日学习任务海报信息错误");
//            }
//            PlayBillDomain p = dailyLearningEx.getPlayBillDomain();
//            p.setPlayBillImageUrl(req.getPlayBillDomain().getPlayBillImageUrl());
//            p.setPlayBillImageUrlQQH5(req.getPlayBillDomain().getPlayBillImageUrlQQH5());
//            update.set("playBillDomain", p);
//
//        }
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, DailyLearning.class);
        return updateResult.getModifiedCount() > 0 ? true : false;
    }

    @Override
    public boolean delete(String id) {
        if (StringUtils.isBlank(id)) {
            log.error(":?>> 删除每日学习参数错误:");
            throw new BusinessException("删除每日学习参数错误");
        }
        Query query = new Query().addCriteria(Criteria.where("dailyLearningId").is(id));
        boolean ex = mongoTemplate.exists(query, UserDailyLearning.class);
        if (ex) {
            log.error(":>>> 用户已经签到,请不要删除:{}", id);
            throw new BusinessException("用户已经签到,请不要删除");
        }
        query = new Query().addCriteria(Criteria.where("id").is(id));
        DeleteResult result = mongoTemplate.remove(query, DailyLearning.class);
        return result.getDeletedCount() > 0 ? true : false;
    }

    @Override
    public Long getUserDailyLearningCount(UserDailyLearning userDailyLearning) {
        log.info(":>>> 获取用户签到数量:{}", JSON.toJSONString(userDailyLearning));
        if (Objects.isNull(userDailyLearning)) {
            log.error(":>>> 获取用户签到数量错误参数");
            throw new BusinessException("获取用户签到数量错误参数");
        }
        Query query = new Query();
        if (StringUtils.isNotBlank(userDailyLearning.getUserId())) {
            query.addCriteria(Criteria.where("userId").is(userDailyLearning.getUserId()));
        }
        if (StringUtils.isNotBlank(userDailyLearning.getTaskId())) {
            query.addCriteria(Criteria.where("taskId").is(userDailyLearning.getTaskId()));
        }
        Long count = mongoTemplate.count(query, UserDailyLearning.class);
        return count;
    }

    @Override
    public PlayBillDomain getPlayBill(UserPO userPO, String id, String appId, String platform) {
        log.info(":>>> 开始获取分享海报 id:{},userPO:{},appId:{},platform:{}", id, JSON.toJSONString(userPO), appId, platform);
        if (StringUtils.isBlank(id) || Objects.isNull(userPO)) {
            log.error(":>>>  获取每日签到分享海报参数错误");
            throw new BusinessException("获取分享海报参数错误");
        }

        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        DailyLearning dailyLearning = mongoTemplate.findOne(query, DailyLearning.class);
        if (Objects.isNull(dailyLearning)) {
            log.error(":>>>  获取分享海报参数错误:每日签到任务不存在");
            throw new BusinessException("获取分享海报参数错误:每日签到任务不存在");
        }
        ActivityInfo activityInfo = activityService.findOne(dailyLearning.getActivityId());
        PlayBillDomain res = dailyLearning.getPlayBillDomain();
        if (Objects.isNull(res)) {
            log.error(":>>> 任务海报信息配置错误:{}");
            throw new BusinessException("任务海报信息配置错误");
        }

        res.setNickName(userPO.getNickName());
        if (Objects.nonNull(userPO) && StringUtils.isBlank(userPO.getAvatarUrl())) {
            userPO.setAvatarUrl(defaultHeadUrl);
        }
        res.setAvatarUrl(userPO.getAvatarUrl());
        String qrCode = platformConfigService.getBizFrontDomain() + platformConfigService.getCatalogue()
                + "index.html#/pages/activity-detial?activityId=" + dailyLearning.getActivityId() +
                "&taskId=" + dailyLearning.getTaskId() + "&appId=" + appId + "&sharedByOpenId=" + userPO.getOpenId() +
                "&theme=" + activityInfo.getThemeColor() + "&sharedByUserId=" + userPO.getId() + "&sPlatform=" + platform;
        res.setQrCode(qrCode);
        if (Objects.nonNull(activityInfo)) {
            res.setTitle(activityInfo.getShareName());
            res.setImgUrl(activityInfo.getShareImageUrl());
            res.setLink(qrCode);
            res.setDesc(activityInfo.getShareOName());
        }
        if (platform.equals("qq-h5") && StringUtils.isNotBlank(res.getPlayBillImageUrlQQH5())) {
            res.setPlayBillImageUrl(res.getPlayBillImageUrlQQH5());
        }
        log.info(":>>> 用户每日签到的海报信息:{}", JSON.toJSONString(res));
        return res;
    }

    /**
     * 运营会不小心忘配签到，导致用户端报错，目前看挺难避免，将用户端展示逻辑修改
     * 1、如果当天日期配置有对应的图片，取该图片
     * 2、如果当天日期未配置，从已配置的图片中随机取一张。
     */
    @Override
    public void autoCreate() {
        // 加锁
        long curDay = System.currentTimeMillis() / 86400;
        String key = String.format("com.youlu.LearningTaskLock:%d", curDay);
        boolean lock = lockService.tryLock(key, 1, TimeUnit.HOURS);
        if (!lock) {
            log.info("获取锁失败，已经执行过自动配置学习签到任务！");
            return;
        }

        try {
            // 查找有效活动
            Timestamp currentDay = TimeUtils.getDayStartTime(new Date());
            Query query = new Query().addCriteria(Criteria.where("endTime").gte(currentDay));
            List<ActivityInfo> activityList = mongoTemplate.find(query, ActivityInfo.class);
            // 查找有效活动的任务
            List<String> activityIdList = activityList.stream().map(activityInfo -> activityInfo.getId()).collect(Collectors.toList());
            query = new Query().addCriteria(Criteria.where("activityId").in(activityIdList).and("taskBizType").is("LEARNING"));
            List<ActivityTaskInfo> taskInfoList = mongoTemplate.find(query, ActivityTaskInfo.class);
            log.info("发现有效活动的有效任务 " + taskInfoList.size() + " 个");
            // 查找每个任务最新的签到活动是否有配置图片，如果没有则自动生成
            for (ActivityTaskInfo taskInfo : taskInfoList) {
                create(taskInfo, currentDay);
            }
        } catch (Exception e) {
            log.error("自动配置学习签到任务发生异常", e.getMessage());
        } finally {
            lockService.unLock(key);
        }
    }

    @Override
    public boolean deleteByActivityId(String activityId) {
        return false;
    }

    public void create(ActivityTaskInfo taskInfo, Timestamp currentDay) {
        try {
            // 如果当天日期未配置，从已配置的图片中随机取一张
            Query query = new Query().addCriteria(Criteria.where("activityId").is(taskInfo.getActivityId()).and("taskId").is(taskInfo.getId()).and("dayTime").is(currentDay));
            DailyLearning dailyLearning = mongoTemplate.findOne(query, DailyLearning.class);
            if (Objects.isNull(dailyLearning)) {
                query = new Query().addCriteria(Criteria.where("activityId").is(taskInfo.getActivityId()).and("taskId").is(taskInfo.getId()));
                // 获取之前配置了多少条
                List<DailyLearning> dailyLearningList = mongoTemplate.find(query, DailyLearning.class);
                log.info("活动之前配置了:" + dailyLearningList.size() + "条" + " activityId:" + taskInfo.getActivityId() + " taskId:" + taskInfo.getId());
                if (dailyLearningList.size() == 0) {
                    return;
                }
                int random = new Random().nextInt(dailyLearningList.size());
                // 随机取一天的配置
                if (dailyLearningList.size() == 1) {
                    dailyLearning = dailyLearningList.get(0);
                    dailyLearning.setDayTime(currentDay);
                    dailyLearning.setId(null);
                    log.info("自动配置学习签到: " + dailyLearning);
                    mongoTemplate.save(dailyLearning);
                } else if (dailyLearningList.size() > 1) {
                    // 从前天开始计算，取之前的随机一天
                    int frontDay = random;
                    if (frontDay < 2) {
                        frontDay = 2;
                    }
                    Date randomDay = TimeUtils.getFrontDay(currentDay, frontDay);
                    query = new Query().addCriteria(Criteria.where("activityId").is(taskInfo.getActivityId()).and("taskId").is(taskInfo.getId()).and("dayTime").is(randomDay));
                    dailyLearning = mongoTemplate.findOne(query, DailyLearning.class);
                    log.info("frontDay:" + frontDay + " size:" + dailyLearningList.size());
                    // 如果取不到，以前的日期有间隔不连续，则从已配置的签到中随机取一个
                    if (Objects.isNull(dailyLearning)) {
                        dailyLearning = dailyLearningList.get(random);
                    }
                    dailyLearning.setDayTime(currentDay);
                    dailyLearning.setId(null);
                    log.info("自动配置学习签到: " + dailyLearning);
                    mongoTemplate.save(dailyLearning);
                } else {
                    log.info("自动学习签到失败，该活动从没配置学习签到！");
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}